package henu.graduation_design.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.SharedPreferences;
import android.os.Handler;

public class JsonLoader {

	private ExecutorService executorService = Executors.newFixedThreadPool(3);
	private final Handler handler = new Handler();

	public void getJsonArray(final String url, final JsonArrayCallback callback) {
		executorService.submit(new Runnable() {
			public void run() {
				try {
					final StringBuilder sb = new StringBuilder();
					HttpClient client = new DefaultHttpClient();
					HttpParams httpParams = client.getParams();
					// 设置网络超时
					HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
					HttpConnectionParams.setSoTimeout(httpParams, 5000);
					HttpResponse response = client.execute(new HttpGet(url));
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(entity.getContent()));
						String line = null;
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						reader.close();
					}

					handler.post(new Runnable() {
						public void run() {
							try {
								callback.jsonLoaded(new JSONArray(sb.toString()));
							} catch (JSONException e) {
							}
						}
					});
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}

	public void getJsonObject(final String url,
			final JsonObjectCallback callback) {
		executorService.submit(new Runnable() {
			public void run() {
				try {
					final StringBuilder sb = new StringBuilder();
					HttpClient client = new DefaultHttpClient();
					HttpParams httpParams = client.getParams();
					// 设置网络超时
					HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
					HttpConnectionParams.setSoTimeout(httpParams, 5000);
					HttpResponse response = client.execute(new HttpGet(url));
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(entity.getContent()));
						String line = null;
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						reader.close();
					}

					handler.post(new Runnable() {
						public void run() {
							try {
								callback.jsonLoaded(new JSONObject(sb
										.toString()));
							} catch (JSONException e) {
							}
						}
					});
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}

	public void postJson(final String url, final SharedPreferences sp ,final Map<String,Object> mapEntity,
			final JsonObjectCallback callback) {
		executorService.submit(new Runnable() {
			public void run() {
				try {
					HttpParams parms = new BasicHttpParams();
					parms.setParameter("charset", HTTP.UTF_8);
					// 设置网络超时
					HttpConnectionParams.setConnectionTimeout(parms, 3000);
					HttpConnectionParams.setSoTimeout(parms, 5000);
					HttpClient httpclient = new DefaultHttpClient(parms);
					HttpPost httppost = new HttpPost(url);
					httppost.addHeader("Content-Type", "*/*");
					httppost.addHeader("charset", HTTP.UTF_8);
					
					List<NameValuePair> formparams = new ArrayList<NameValuePair>();
					if(mapEntity!=null){
					    for(Entry<String, Object> e : mapEntity.entrySet()){
	                        formparams.add(new BasicNameValuePair(e.getKey(), e.getValue().toString()));   
	                    }
					}
                    if(sp!=null){
                        formparams.add(new BasicNameValuePair("userName", sp.getString("UserName", "")));
                        formparams.add(new BasicNameValuePair("password", sp.getString("UserName", "")));
                        formparams.add(new BasicNameValuePair("userID", String.valueOf(sp.getInt("UserID", 0))));   
                    }
                    UrlEncodedFormEntity entrity=new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
                    httppost.setEntity(entrity);    

					HttpResponse response;
					response = httpclient.execute(httppost);
					int code = response.getStatusLine().getStatusCode();
					final String rev;
					if (code == 200 && response.getEntity() != null) {
						rev = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);
					} else {
						rev = "";
					}
					handler.post(new Runnable() {
						public void run() {
							try {
								callback.jsonLoaded(new JSONObject(rev
										.toString()));
							} catch (JSONException e) {
							}
						}
					});
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}

	public void postJson(final String url,final SharedPreferences sp, final Map<String,Object> mapEntity,
			final JsonArrayCallback callback) {
		executorService.submit(new Runnable() {
			public void run() {
				try {
					HttpParams parms = new BasicHttpParams();
					parms.setParameter("charset", HTTP.UTF_8);
					// 设置网络超时
					HttpConnectionParams.setConnectionTimeout(parms, 3000);
					HttpConnectionParams.setSoTimeout(parms, 5000);
					HttpClient httpclient = new DefaultHttpClient(parms);
					HttpPost httppost = new HttpPost(url);
					httppost.addHeader("Content-Type", "*/*");
					httppost.addHeader("charset", HTTP.UTF_8);
					
				    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
				    
				    if(mapEntity!=null){
    				    for(Entry<String, Object> e : mapEntity.entrySet()){
    				        formparams.add(new BasicNameValuePair(e.getKey(), e.getValue().toString()));   
    				    }
				    }
				    if(sp!=null){
				        formparams.add(new BasicNameValuePair("userName", sp.getString("UserName", "")));
	                    formparams.add(new BasicNameValuePair("password", sp.getString("UserName", "")));
	                    formparams.add(new BasicNameValuePair("userID", String.valueOf(sp.getInt("UserID", 0))));   
				    }
				    UrlEncodedFormEntity entrity=new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
					httppost.setEntity(entrity);
					
					HttpResponse response;
					response = httpclient.execute(httppost);
					int code = response.getStatusLine().getStatusCode();
					final String rev;
					if (code == 200 && response.getEntity() != null) {
						rev = EntityUtils.toString(response.getEntity(),HTTP.UTF_8);
					} else {
						rev = "";
					}
					handler.post(new Runnable() {
						public void run() {
							try {
								callback.jsonLoaded(new JSONArray(rev
										.toString()));
							} catch (JSONException e) {
							}
						}
					});
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}

	// 对外界开放的回调接口
	public interface JsonArrayCallback {
		public void jsonLoaded(JSONArray jsonArray);
	}

	// 对外界开放的回调接口
	public interface JsonObjectCallback {
		public void jsonLoaded(JSONObject jsonObject);
	}
}
